﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Sprout.Schedule.Web.Extensions;
using Sprout.Schedule.Web.Exceptions;
using Sprout.Schedule.Web.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;


namespace Sprout.Schedule.Web.Attributes
{
    public class ExceptionFilterAttribute : Attribute, IAsyncExceptionFilter
    {
        /// <summary>
        /// 全局异常处理
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public Task OnExceptionAsync(ExceptionContext context)
        {
            if (context.HttpContext.Request.IsAjaxRequest())
            {
                //标识异常已处理
                context.ExceptionHandled = true;

                if (context.Exception is WException exception)
                {
                    //自定义异常
                    if (exception.HttpStatusCode == HttpStatusCode.OK)
                    {
                        context.Result = new ObjectResult(new ResponseResult
                        {
                            StatusCode = exception.StatusCode,
                            Message = exception.Message
                        });
                    }
                    else
                    {
                        //如果指定了 HTTP状态码
                        context.Result = new JsonResult(exception.Message)
                        {
                            StatusCode = (int)exception.HttpStatusCode
                        };
                    }
                }
                else
                {
                    context.Result = new ObjectResult(new ResponseResult
                    {
                        StatusCode = StatusCodeEnum.Error,
                        Message = context.Exception.Message
                    });
                }
            }

            return Task.CompletedTask;
        }
    }
}
